import 'package:flutter/material.dart';
import 'package:library_base/widget/multi_state_widget/multi_controller.dart';
import 'package:library_base/widget/multi_state_widget/multi_loading.dart';

class MultiStateWidget extends StatefulWidget {
  Widget? loadingWidget;

  Widget? errorWidget;

  Widget? emptyWidget;

  MultiController? controller;

  Future<bool>? future;

  Widget? child;

  late Widget Function()? buildChild;

  MultiStateWidget(
      {this.child,
      Key? key,
      this.loadingWidget,
      this.errorWidget,
      this.emptyWidget,
      this.controller,
        this.buildChild,
      })
      : super(key: key) {
    loadingWidget = loadingWidget ?? MultiLoading();
    errorWidget = errorWidget ?? Container(color: Colors.red);
    emptyWidget = emptyWidget ?? Container(color: Colors.lightBlueAccent);
  }

  @override
  State<StatefulWidget> createState() {
    return _MultiStateWidgetState();
  }
}

class _MultiStateWidgetState extends State<MultiStateWidget> {
  @override
  void initState() {
    super.initState();
    widget.controller?.addListener(() {
      setState(() {});
    });
  }

  @override
  void dispose() {
    super.dispose();
    widget.controller?.dispose();
  }

  @override
  Widget build(BuildContext context) {
    var initStatus =
        widget.controller != null ? widget.controller!.initStatus : MultiStateStatus.loading;
    return AnimatedSwitcher(
        duration: const Duration(milliseconds: 300), child: switcherWidget(initStatus));
  }

  Widget switcherWidget(MultiStateStatus initStatus) {
    if (initStatus == MultiStateStatus.loading) {
      return widget.loadingWidget!;
    } else if (initStatus == MultiStateStatus.error) {
      return widget.errorWidget!;
    } else if (initStatus == MultiStateStatus.empty) {
      return widget.emptyWidget!;
    } else {
      return widget.child??widget.buildChild?.call()??Container();
    }
  }

}

enum MultiStateStatus {
  loading, //加载中视图
  error, //失败视图
  empty, //没有数据视图
  content, //成功加载数据视图
}
